<!DOCTYPE html>
<html>
<head>
	<title>mzflaskfive</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, 
                                     initial-scale=1.0, 
                                     maximum-scale=1.0, 
                                     user-scalable=no">
	<!-- 引入jquery和bootstrap -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
	<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
	<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
	

</head>
<body onload="run();">
	<div class="container" style="padding: 0;">
		<div class="container" style="padding: 0;text-align: center;">
			<h1>mzflaskfive</h1>
		</div>
		<canvas id="myCanvas" width="800" height="800" style="display: block; margin: 0 auto;padding: 0;"></canvas>
		
		<div class="container">
			<div style="margin-top: 10px;">
				<button class="btn btn-default" onclick="window.location.href='?r='+Math.random();">Reset</button>
				<button class="btn btn-default">Help</button>
				<button class="btn btn-default" id='change_mode'>Change Mode</button><br>
				<p>game mode:<span id='mode'>PvP</span></p>
			</div>
		</div>
	</div>

	<!-- 图片素材预加载，为隐藏类型 -->
	<img src="{{ url_for('static', filename='chessboard.jpg') }}" id='chessboard' style="display: none;">
	<img src="{{ url_for('static', filename='black.png') }}" id='black' style="display: none;">
	<img src="{{ url_for('static', filename='white.png') }}" id='white' style="display: none;">
		
		
	
</body>

<script type="text/javascript">
	// 这里放全局变量
	// game 对象的构造器函数
	// 棋盘上0表示没有棋子，1表示黑，2表示白
	function Game() {
		this._get_mouse = function(e){
			// var rect = canvas.getBoundingClientRect();
			// var mouseX = e.clientX - rect.left;
			// var mouseY = e.clientY - rect.top;
			if(e.offsetX) {
		        mouseX = e.offsetX;
		        mouseY = e.offsetY;
		    }else if(e.layerX) {
		        mouseX = e.layerX;
		        mouseY = e.layerY;
		    }
		    return {x: mouseX, y: mouseY }
		};


		// 检查棋盘，判定游戏结果
		this._check = function(){
			var end = false;  // 是否结束了
			for (let i = 0; i < 15; i ++){
				for (let j = 0; j < 15; j ++){
					if (this.chessboard[i][j] != 0){
						// 存在棋子，开始判定
						let who = this.chessboard[i][j];
						// 横5
						if (j <= 10){
							if (who == this.chessboard[i][j+1] 
								&& who == this.chessboard[i][j+2]
								&& who == this.chessboard[i][j+3]
								&& who == this.chessboard[i][j+4]){
								end = true;
								this.winner = who;
								break;
							}
						}
						// 竖5
						if (i <= 10){
							if (who == this.chessboard[i+1][j] 
								&& who == this.chessboard[i+2][j]
								&& who == this.chessboard[i+3][j]
								&& who == this.chessboard[i+4][j]){
								end = true;
								this.winner = who;
								break;
							}
						}
						// 左斜
						if (i <= 10 && j >= 4){
							if (who == this.chessboard[i+1][j-1] 
								&& who == this.chessboard[i+2][j-2]
								&& who == this.chessboard[i+3][j-3]
								&& who == this.chessboard[i+4][j-4]){
								end = true;
								this.winner = who;
								break;
							}
						}
						// 右斜
						if (j <= 10 && i <= 10){
							if (who == this.chessboard[i+1][j+1] 
								&& who == this.chessboard[i+2][j+2]
								&& who == this.chessboard[i+3][j+3]
								&& who == this.chessboard[i+4][j+4]){
								end = true;
								this.winner = who;
								break;
							}
						}
					}
				}
				if (end == true){
					break;
				}
			}

			if (end == true){
				this.status = 'end';   // 状态修改为游戏结束
			}
		};

		this._get_choice = function(){
			// 从后端获取该走什么棋
			// 将棋局序列化
			var chessboardstr = '';
			for (let i = 0; i < 15; i ++){
				for (let j = 0; j < 15; j ++){
					chessboardstr += this.chessboard[i][j];
				}
			}
			console.log(chessboardstr);
			// 直接发送棋局
			var that = this;
			$.post("/",
				'chessboardstr='+chessboardstr,
				function(data,status){
					// alert("Data: " + data);
					choice = JSON.parse(data);
					console.log('ai think:'+choice);
		    		that.chessboard[choice[1]][choice[0]] = that.player;
		    		that._change_player();
		    		// 重绘画布
			    	that.mzCanvas.repaint(that.chessboard);
			    	// 检查棋局
			    	that._check();
			    	if (that.status == 'end'){
			    		// 宣布胜利者
			    		if (that.winner == 1){
			    			alert('black wins！');
			    		}else{
			    			alert('white wins！');
			    		}
			    		
			    	}
				}
			);
		};

		this._change_player = function(){
			if (this.player == 2){
		    	this.player = 1;
		    }else{
		    	this.player = 2;
		    }
		}

	    this.chessboard = [
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	    	];
	    this.player = 1;       // 黑棋先走
	    this.winner = 0;           // 获胜者
	    this.status = 'playing';   // 游戏中
	    this.mode = 1;                    // 游戏模式PvP/PvE/EvP    初始化为PvP
	    this.mode_list = ['PvP', 'PvE', 'EvP'];
	    $("#mode").html(this.mode_list[this.mode]);

	    this.mzCanvas = new MzCanvas();
	    this.mzCanvas.init_ui();    // 初始化UI
		this.mzCanvas.repaint(this.chessboard);      // 重绘画面


		// 棋盘点击事件
		var that = this;
		this.mzCanvas.canvas.onclick = function(e){
			var mouse = that._get_mouse(e);
			console.log(mouse);
			var imgchessboard = document.getElementById("chessboard");
			var imgblack = document.getElementById("black");
			var imgwhite = document.getElementById("white");
			var chess_size = (imgblack.width+3) / imgchessboard.width * that.mzCanvas.WIDTH;
	    	var border = 2 / imgchessboard.width * that.mzCanvas.WIDTH;

	    	var x = parseInt((mouse.x - border)/chess_size);
	    	var y = parseInt((mouse.y - border)/chess_size);
	    	console.log('x='+x+',y='+y);

	    	// 走棋
	    	if (that.chessboard[y][x] == 0 && that.status == 'playing'){  // 这个位置没有棋
	    		that.chessboard[y][x] = that.player;
		    	// 玩家转换
		    	that._change_player();

		    	// 重绘画布
		    	that.mzCanvas.repaint(that.chessboard);
		    	// 检查棋局
		    	that._check();

		    	// 检查游戏模式，如果是PvE或者EvP就让电脑走棋
		    	if (that.mode != 0 && that.status == 'playing'){
		    		that._get_choice();         // 获取电脑思考结果并走棋和切换和check
		    	}

		    	if (that.status == 'end'){
		    		// 宣布胜利者
		    		if (that.winner == 1){
		    			alert('black wins！');
		    		}else{
		    			alert('white wins！');
		    		}
		    		
		    	}
	    	}
		}

		// 更换模式的监听
		document.getElementById('change_mode').onclick = function(){
			that.mode = (that.mode+1)%3;
			$("#mode").html(that.mode_list[that.mode]);
			// 重置棋局
			// ...
		}
	}

	// 画布类
	// 下划线开头的属于内部方法
	function MzCanvas(){
		this.HEIGHT = 700;
		this.WIDTH = 700;
		this.canvas = document.getElementById("myCanvas");       // 获取canvas对象
		this.imgchessboard = document.getElementById("chessboard");
		this.imgblack = document.getElementById("black");
		this.imgwhite = document.getElementById("white");



		this._IsPhone = function(){
			//获取浏览器navigator对象的userAgent属性（浏览器用于HTTP请求的用户代理头的值）
	        var info = navigator.userAgent;
	        console.log(navigator.userAgent);
	        //通过正则表达式的test方法判断是否包含“Mobile”字符串
	        var isPhone = /mobile|Android|Phone/i.test(info);
	        //如果包含“Mobile”（是手机设备）则返回true
	        return isPhone;
		};

		this.init_ui = function(){
			// 初始化界面
			if(this._IsPhone()){
	    		// 如果是手机端
	    		console.log('手机端');
	    		// 游戏显示的大小要根据设备宽度来定
	    		let width = document.documentElement.clientWidth;
				let height = document.documentElement.clientHeight;
				console.log('屏幕大小:'+width+'*'+height);
				// 设置变量
				this.HEIGHT = width;
				this.WIDTH = width;
				// 重新调整canvas宽高
				this.canvas.setAttribute("width",this.WIDTH);
				this.canvas.setAttribute("height",this.HEIGHT);    // 设置正方形
				
	    	}else{
	    		console.log('电脑端')
	    		this.canvas.setAttribute("width",this.WIDTH);
				this.canvas.setAttribute("height",this.HEIGHT);    // 设置正方形
	    	}
		};

		// 绘制背景
		this._draw_bg = function (){
			var ctx = this.canvas.getContext("2d");
			// ctx.fillStyle = "#000000";
			// ctx.fillRect(0, 0, this.WIDTH, this.HEIGHT);    // 填充背景
			ctx.drawImage(this.imgchessboard, 0,0, this.WIDTH, this.HEIGHT);

	    };

	    // 绘制棋子
	    this._draw_chess = function(chessboard){
	    	var ctx = this.canvas.getContext("2d");
	    	var chess_size = (this.imgblack.width+3) / this.imgchessboard.width * this.WIDTH;
	    	var border = 2 / this.imgchessboard.width * this.WIDTH;
	    	for (let i = 0; i < 15; i ++) {
	    		for (let j = 0; j < 15; j ++){
	    			if (chessboard[i][j] == 0) {
	    				// do nothing
	    			}else if (chessboard[i][j] == 1) {   // black
	    				ctx.drawImage(this.imgblack, border+j*chess_size, border+i*chess_size, chess_size, chess_size);
	    			}else if (chessboard[i][j] == 2) {    // white
	    				ctx.drawImage(this.imgwhite, border+j*chess_size, border+i*chess_size, chess_size, chess_size);
	    			}
	    		}
	    	}
	    };

	    this.repaint = function(chessboard){
	    	// 重绘画面
	    	this._draw_bg();    // 绘制背景
	    	this._draw_chess(chessboard);
	    };
	}
    
	// // 检测用户按键
	// document.onkeydown=function(event)
	// {
	// 	// console.log('keydown: '+ event.keyCode);
	// 	if ( event.keyCode=='87' ) //w
	// 	{
	// 		mov('w');
	// 	}else if(event.keyCode=='65' ){ // a
	// 		mov('a');
	// 	}else if(event.keyCode=='83' ){ // s
	// 		mov('s');
	// 	}else if(event.keyCode=='68' ){ // d
	// 		mov('d');
	// 	}
	// }	
</script>

<script type="text/javascript">
	function run(){
		var game = new Game();        // 创建game对象
	}
	
</script>
</html>